package com.igeek.compus.test.system.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

//@WebFilter(filterName = "f2", urlPatterns = "*.jsp")
public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("----------login filter-------------");

        // 类型转换
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpSession session = httpServletRequest.getSession();

        String servletPath = httpServletRequest.getServletPath();
        System.out.println(servletPath);

        // 如果是登陆页面或者是注册页面，直接放行
        if(servletPath.contains("login") || servletPath.contains("register")) {
            filterChain.doFilter(servletRequest, servletResponse);
        }else {
            // 校验登陆，获得session中的user，如果没有，则未登陆，跳转至登陆页面
            Object user = session.getAttribute("user");
            if (user == null) {
                httpServletRequest.setAttribute("msg", "请先登陆");
                httpServletRequest.getRequestDispatcher("login.jsp").forward(servletRequest, servletResponse);
            }
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {

    }
}
